﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Web;
using BO.Infrastructure.StaticData;
using BO.Infrastructure.Utils;
using BO.News;
using BugManager;
using ChannelVN.Cached;
using ChannelVN.Cached.Base;
using ChannelVN.Cached.UrlRewrite;
using GUI.Extensions;
using Utilities.Entities;

namespace GUI.Pages.News
{
    public partial class NewsDetail : PageBase
    {
        #region Overrides of PageBase

        protected override string CacheConfigName
        {
            get { return "Pages-News-NewsDetail"; }
        }

        protected override bool IsCachedChanged(long newsId, string zoneId, long tagId)
        {
            return false;
        }

        #endregion

        private const int TopHotNews = 12;

        public long NewsId = 0;
        public int ZoneId = 0;

        /// <summary>
        /// Những catId dùng để thay thế nếu category lấy theo catUrl không còn tồn tại.
        /// eg: 
        /// requestUrl = "/hinh-su/news-title-123.htm
        /// >> cat hình sự nếu không tồn tại thì sẽ sử dụng catId được chỉ định thay thế để get/bind data.
        /// </summary>
        private static readonly Dictionary<string, int> CatRepresent = new Dictionary<string, int>
            {
                {"hinh-su",10015},  //>> pháp luật
                {"san-pham-moi",10020}  //>> công nghệ
            };

        protected void Page_Load(object sender, EventArgs e)
        {
            var newsId = RequestExtensions.NewsId;

            if (newsId > 0)
            {
                NewsObject objNews = null;

                var bo = CacheSettingExtensions.EnableCacheHtml ? NewsBO_NoCache.GetInstance() : NewsBO.GetInstance();
                var interviewId = 0;

                #region First time
                if (string.IsNullOrEmpty(ctrNewsDetail.CacheData) || CacheController.IsCachedUpdating)
                {
                    var dt = bo.GetNewsDetail(newsId);

                    if (dt != null && dt.Rows.Count > 0)
                    {
                        var r = dt.Rows[0];
                        var type = PresentationUtils.Object2Integer(r[SqlConstants.NewsPublish.Type].ToString());

                        if (type == DefinedConstants.News.TypeIDs.BaiGiaoLuuTrucTuyen)
                            interviewId = NewsBO.GetInstance().GetInterviewId(newsId);

                        ctrNewsDetail.Visible = ctrNewsDetail.DataBind(dt, interviewId);


                        var tagItems = r[SqlConstants.NewsPublish.TagItem].ToString().Replace(';', ',');
                        var originalUrl =
                            PresentationUtils.UrlBuilder.BuildAbsoluteUrl(
                                 dt.Columns.Contains(SqlConstants.NewsPublish.OriginalUrl) && !string.IsNullOrEmpty(r[SqlConstants.NewsPublish.OriginalUrl].ToString())
                                    ? r[SqlConstants.NewsPublish.OriginalUrl].ToString()
                                    : r[SqlConstants.NewsPublish.Url].ToString());

                        objNews = new NewsObject
                        {
                            NewsId = newsId,
                            Title = r[SqlConstants.NewsPublish.Title].ToString(),
                            Avatar = r[SqlConstants.NewsPublish.Avatar].ToString(),
                            DetailedAvatar = PresentationUtils.Photo.GetSourceImage(r[SqlConstants.NewsPublish.Avatar].ToString()),
                            DistributionDate = PresentationUtils.Object2DateTime(r[SqlConstants.NewsPublish.DistributionDate].ToString()),
                            Sapo = r[SqlConstants.NewsPublish.Sapo].ToString(),
                            Description = r[SqlConstants.NewsPublish.Sapo].ToString(),
                            Url = r[SqlConstants.NewsPublish.Url].ToString(),
                            OriginalUrl = originalUrl,
                            ShortUrl = PresentationUtils.UrlBuilder.BuildAbsoluteUrl(Regex.Replace(r[SqlConstants.NewsPublish.Url].ToString(), @"([^/]+)(-)(\d+)", "n$2$3")),
                            DetailedUrl = PresentationUtils.UrlBuilder.BuildAbsoluteUrl(r[SqlConstants.NewsPublish.Url].ToString()),
                            Keywords = tagItems,
                            NewsKeywords = tagItems,
                            Base64Title = PresentationUtils.EncodeBase64(HttpUtility.UrlEncode(r[SqlConstants.NewsPublish.Title].ToString())),
                            ZoneId = PresentationUtils.Object2Integer(r[SqlConstants.NewsPublish.ZoneId].ToString()),
                            Type = type
                        };
                        NewsBO.AddNewsMetaData(objNews);
                    }
                }
                #endregion

                if (objNews == null)
                {
                    objNews = NewsBO.GetNewsMetaData(newsId);
                }

                if (objNews != null)
                {
                    if (!Request.RawUrl.StartsWith(objNews.Url) && !(CacheController.IsCachedDeleting || CacheController.IsCachedUpdating))
                    {
                        _301Redirection.RedirectTo(objNews.Url);
                        return;
                    }
                    PresentationUtils.SetCanonicalLink(Page, objNews.DetailedUrl);
                    PresentationUtils.AddFacebookMetaData(Page, DefinedConstants.Social.Types.Article, objNews.OriginalUrl, objNews.Title, objNews.DetailedAvatar, objNews.Sapo);
                    PresentationUtils.ChannelVN.RegisterReportValues(Page, objNews.NewsId, objNews.ZoneId);

                    NewsId = objNews.NewsId;
                    ZoneId = objNews.ZoneId;

                    //bài giao lưu
                    if (objNews.Type == DefinedConstants.News.TypeIDs.BaiGiaoLuuTrucTuyen)
                    {
                        if (interviewId <= 0)
                            interviewId = NewsBO.GetInstance().GetInterviewId(objNews.NewsId);
                        if (interviewId > 0)
                        {
                            var dtGiaoLuuTrucTuyen = NewsBO.GetInstance().GetBaiGiaoLuuTrucTuyen(interviewId);
                            if (dtGiaoLuuTrucTuyen != null && dtGiaoLuuTrucTuyen.Rows.Count > 0)
                            {
                                var status = PresentationUtils.Object2Integer(dtGiaoLuuTrucTuyen.Rows[0]["Status"].ToString());
                                
                                if (status != 1) //da bat dau hoac ket thuc
                                {
                                    ctrGiaoLuuTrucTuyen.Visible =  ctrGiaoLuuTrucTuyen.DataBind(dtGiaoLuuTrucTuyen, objNews.DistributionDate,
                                                                 objNews.DetailedUrl, interviewId, status == 3);
                                }
                            }
                        }
                    }
                    ctrNewsDetail.Visible = !ctrGiaoLuuTrucTuyen.Visible;

                    //box comment
                    ctrBoxComment.DetailedUrl = objNews.DetailedUrl;
                    ctrBoxComment.SortUrl = objNews.ShortUrl;
                    ctrBoxComment.EncodedBase64Title = objNews.Base64Title;

                    //google snippet
                    ctrGoogleSnippet.Url = objNews.DetailedUrl;
                    ctrGoogleSnippet.Avatar = objNews.DetailedAvatar;
                    ctrGoogleSnippet.Title = objNews.Title;
                    ctrGoogleSnippet.Description = objNews.Sapo;
                    ctrGoogleSnippet.RateCount += objNews.DistributionDate.Hour * 13;


                    #region NewsMetaData cho SEO
                    var newsMetaData = NewsBO.GetInstance().SEO_GetNewsDetail(newsId);
                    if (newsMetaData != null)
                    {
                        if (string.IsNullOrEmpty(newsMetaData.Title))
                            newsMetaData.Title = objNews.Title;
                        if (string.IsNullOrEmpty(newsMetaData.Description))
                            newsMetaData.Description = objNews.Sapo;
                        if (string.IsNullOrEmpty(newsMetaData.Keywords))
                            newsMetaData.Keywords = objNews.Keywords;
                        if (string.IsNullOrEmpty(newsMetaData.NewsKeywords))
                            newsMetaData.NewsKeywords = objNews.Keywords;
                    }
                    else
                    {
                        newsMetaData = objNews;
                    }
                    PresentationUtils.AddMeta(Page, DefinedConstants.MetaAttributes.Description.Id, DefinedConstants.MetaAttributes.Description.Name, newsMetaData.Description);
                    PresentationUtils.AddMeta(Page, DefinedConstants.MetaAttributes.Keywords.Id, DefinedConstants.MetaAttributes.Keywords.Name, newsMetaData.Keywords);
                    PresentationUtils.AddMeta(Page, DefinedConstants.MetaAttributes.NewsKeywords.Id, DefinedConstants.MetaAttributes.NewsKeywords.Name, newsMetaData.NewsKeywords);
                    #endregion

                    Page.Header.Title = string.Format("{0} | soha.vn", newsMetaData.Title);

                    var objCat = RequestExtensions.Category;
                    var catParentId = 0;
                    if (objCat != null)
                    {
                        catParentId = objCat.ParentId > 0 ? objCat.ParentId : objCat.Id;
                        var isSport = catParentId == DefinedConstants.Zone.TheThao;

                        #region SubMenu
                        {
                            try
                            {
                                phSubCategories.Controls.Add(isSport
                                                                 ? LoadControl("~/Controls/Sport/SubCategories.ascx")
                                                                 : LoadControl("~/Controls/News/SubCategories.ascx"));
                            }
                            catch (Exception ex)
                            {
                                ErrorManager.Log(ex.ToString());
                            }
                        }
                        #endregion
                    }
                    else
                    {
                        var catUrl = RequestExtensions.CatUrl;
                        if (CatRepresent.ContainsKey(catUrl))
                            catParentId = CatRepresent[catUrl];
                    }

                    #region Top slide
                    if (string.IsNullOrEmpty(ctrSlide.CacheData) || CacheController.IsCachedUpdating)
                    {
                        var dt = bo.GetHotNews(top: TopHotNews, zoneId: catParentId);
                        if (dt == null || dt.Rows.Count == 0)
                        {
                            ctrSlide.Visible = false;
                        }
                        else
                        {
                            ctrSlide.Visible = ctrSlide.DataBind(dt);
                        }
                    }
                    #endregion

                    #region Box có thể bạn quan tâm
                    if (string.IsNullOrEmpty(ctrCoTheBanQuanTam.CacheData) || CacheController.IsCachedUpdating)
                    {
                        var dt = bo.GetEmbedNewsOnPage(3, catParentId, 2);
                        if (dt == null || dt.Rows.Count == 0)
                        {
                            ctrCoTheBanQuanTam.Visible = false;
                        }
                        else
                        {
                            ctrCoTheBanQuanTam.Visible = ctrCoTheBanQuanTam.DataBind(dt);
                        }

                    }
                    #endregion

                    #region Box đọc nhiều nhất
                    if (string.IsNullOrEmpty(ctrDocNhieuNhat.CacheData) || CacheController.IsCachedUpdating)
                    {
                        ctrDocNhieuNhat.Visible = ctrDocNhieuNhat.DataBind(NewsBO.GetInstance().GetCareableNews(6));
                    }
                    #endregion

                    #region Css/Js
                    {
                        var objCatMetaData = NewsBO.GetInstance().GetCategoryMetaData(catParentId);
                        if (objCatMetaData != null && !string.IsNullOrEmpty(objCatMetaData.ThemeUrl))
                        {
                            PresentationUtils.AddCss(Page, objCatMetaData.ThemeUrl, usingMasterPageVersion: true, isTheme: true);
                        }
                    }
                    #endregion

                    return;
                }
            }
            if (!string.IsNullOrEmpty(Request.RawUrl))
            {

                if (Regex.IsMatch(Request.RawUrl, "/([^/]+)/([^/]+)-([0-9]+).htm"))
                {
                    string suggest;
                    try
                    {
                        suggest = Regex.Split(Request.RawUrl, "/([^/]+)/([^/]+)-([0-9]+).htm")[2];
                    }
                    catch
                    {
                        suggest = string.Empty;
                    }
                    _301Redirection.RedirectToFileNotFoundPage(suggest);
                    return;
                }

            }
            _301Redirection.RedirectToFileNotFoundPage();
        }
    }
}
